<?php

namespace App\Controller\User;

use Usap\Service\Service;

/**
 * zhangxw
 * @desc 方案详情
 */
class ProjectController extends AbstractController
{
    private $projectId = '';
    private $userId = '';

    public function __construct()
    {
        parent::__construct();
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $this->projectId = $param_list['pid'];
//        var_dump($param_list);die;
//        $this->projectId = '1102';
        $this->userId = $this->context->userId;

// 		if(empty($this->userId)){
// 			$from = '/account/login?from='.rawurlencode('/project/'.$this->projectId);
// 			redirect($from);
// 		}
        if (!is_numeric($this->projectId)) {
            $this->ajaxReturn(array('code' => '1001', 'code_str' => '参数错误!'));
        }
    }

    /*
    * 入口
    */
    public function index()
    {
        $lotteryServer = Service::instance()->find('lottery', 'lottery');
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $type = $param_list['type'];
        $projectInfo = $lotteryServer->getLotteryInfo($this->projectId);
        $lotteryType = $projectInfo['lotteryType'];

        if (empty($projectInfo) || $projectInfo['code'] == -1002) {
            $this->ajaxReturn(array('code' => '1001', 'code_str' => '此方案不存在或者已超过3个月的保存期限，暂时无法查询，由此带来的不便，敬请谅解!'));
        }
        $levelInfo = Service::instance()->loadConfig('lottery', 'lottery', 'getLotteryLevel', array($projectInfo['lotteryType']));
        $className = 'Project_' . $levelInfo['1'] . '_' . $projectInfo['lotteryType'];
         if (class_exists($className)) {
            $projectClass = new $className();
            $projectClass->run($projectInfo, $levelInfo);

            $projectClass->setWagerTpl();
            $projectInfo = $projectClass->setLotteryResultTpl();
            $projectInfo['wagerList'] = $projectInfo['wagerStr'];
            unset($projectInfo['wagerStr']);
            if (is_array($projectInfo['wagerList'])) {
                $projectInfo['wagerList'] = array_merge($projectInfo['wagerList']);
            }
//            dprint($projectInfo);
            $str = $this->encrypt($projectInfo);//加密
            $this->ajaxReturn(array("code" => "0000", 'code_str' => '获取信息成功', 'info' => $str));
        }
        $this->ajaxReturn(array('code' => '-1001', 'code_str' => '此方案不存在'));
    }

    //方案进度
    public function pace()
    {

        $lottery_service = Service::instance()->find('lottery', 'lottery');
        $ticket_service = Service::instance()->find('ticket', 'ticket');

        $lottery_info = $lottery_service->getLotteryInfo($this->projectId);

        $except_prize_time = $lottery_service->getExpectPrizeTime($this->projectId);//方案预计开奖时间
        $lottery_type = $lottery_info['lotteryType'];//彩种类型
        $lottery_no = $lottery_info['lotteryNo'];//期号
        $sell_end_time = $lottery_info['printEndTime'];//销售截至购买时间
        $pay_status = $lottery_info['goodsStatus'];//支付状态

        $consign_type = $lottery_info['consignType'];//购买方式
        $create_time = $lottery_info['addTime'];//方案创建时间

        $pay_time = $lottery_service->getPayTime($this->projectId);//付款时间
//        dprint($this->projectId);
        $print_status = $lottery_info['printed'];//出票状态

        //定义方案有无票数据
        $is_havingticket = 'N';
        $ticket_info = $ticket_service->getTicketDataByLotteryId($this->projectId);
        if ($ticket_info['count'] > 0 && $print_status == 'yes') {
            $is_havingticket = 'Y';
        }


        $fail_time = $lottery_info['failTime'];//方案失败时间(过期未付、票全部失败)
        $printed_time = $lottery_info['ticketDownTime'];//出票时间(含部分)


        $real_money = $lottery_info['realMoney']; //实际出票金额
        $money = $lottery_info['totalMoney'];//方案金额

        $prize_status = $lottery_info['prizeStatus'];//方案开奖状态
        $open_time = $lottery_info['openTime'];//开奖时间
        $prize_time = $lottery_info['ticketPrizeTime'];//派奖时间
        $net_prize = $lottery_info['netPrize'];//税后奖金
        $raw_prize = $lottery_info['rawPrize'];//税前奖金
        $real_prize = $lottery_info['realPrize'];//实际出票奖金

        $get_ticket = $lottery_info['getTicketSelf'];
        /**
         * 定义方案状态详情中5个状态
         */
        $submit_info = array(//提交
            'msg' => '提交订单',
            'time_desc' => date('y-m-d H:i', strtotime($lottery_info['addTime'])),
        );

        $pay_info = array(//付款
            'msg' => '等待付款',
            'time_desc' => date('y-m-d H:i', strtotime($sell_end_time)),
        );

        $print_info = array(//出票
            'msg' => '未出票',
            'time_desc' => date('y-m-d H:i', strtotime($sell_end_time)),
        );

        $open_info = array(//开奖
            'msg' => '未开奖',
            'time_desc' => date('y-m-d H:i', strtotime($except_prize_time)),
        );

        $dispatch_info = array(//派奖
            'msg' => '未派奖',
            'time_desc' => date('y-m-d H:i', strtotime($except_prize_time) + 20 * 60),//保守预计开奖时间＋20分钟
        );

        //@TODO 后面考虑集成到方法中
        if ($pay_status == 'not' || $pay_status == 'on') {//等待付款

            $pay_info['time_desc'] = $pay_info['time_desc'] . ' 截至';
            $print_info['time_desc'] = $print_info['time_desc'] . ' 截至';
            $open_info['time_desc'] = '预计 ' . $open_info['time_desc'] . ' 开奖';
            $dispatch_info['time_desc'] = '预计 ' . $dispatch_info['time_desc'] . ' 派奖';


            $process_status = 'submit';//进度条状态

            $current_status = 'paying';//底部状态

            $current_statuscn = '立即付款';//底部状态

            //@TODO $consign_type针对不同支付方式，可能后续展示不一样
            if (strtotime($fail_time) > strtotime($lottery_info['addTime'])) {//过期未付情况

                $pay_info['time_desc'] = date('y-m-d H:i', strtotime($fail_time));
                $process_status = 'pay';

                $current_status = 'close';
                $current_statuscn = '交易关闭';
            }

            if (time() > strtotime($sell_end_time)) {

                $print_info['msg'] = '不出票';
                $process_status = 'printing';

                if (in_array($prize_status, array('Open', 'Prize')) && !empty($open_time)) {//开奖

                    $open_info = array(
                        'time_desc' => date('y-m-d H:i', strtotime($open_time)),
                        'msg' => ($raw_prize <= 0) ? '未中奖' : ($net_prize != $raw_prize ? '大奖 ' . $net_prize : '中奖 ' . $net_prize),
                    );

                    $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($open_time));

                    $process_status = 'dispatch';
                }
            }
        } elseif ($pay_status == 'deal') {//付款成功

            $process_status = 'printing';

            $current_status = 'printing';

            $current_statuscn = '等待出票';

            $pay_info = array(
                'msg' => '付款成功',
                'time_desc' => date('y-m-d H:i', strtotime($pay_time)),
            );
            $print_info['msg'] = '等待出票';


            if (strtotime($printed_time) > strtotime($create_time) || strtotime($fail_time) > strtotime($create_time)) {//经过出票环节

                $process_status = 'opening';

                $open_info['msg'] = '待开奖';
                $open_info['time_desc'] = '预计 ' . $open_info['time_desc'];

                $dispatch_info['time_desc'] = '预计 ' . $dispatch_info['time_desc'];

                if ($print_status == 'yes') {//出票成功

                    $current_status = 'succ';
                    $current_statuscn = '交易成功';

                    $print_info['time_desc'] = date('y-m-d H:i', strtotime($printed_time));
                    if ($real_money == $money) {

                        $print_info['msg'] = '出票成功';
                    } else {
                        $print_info['msg'] = '部分成功';

                        $current_status = 'succ';
                        $current_statuscn = '部分成功';
                    }
                } else {//异常情况
                    $process_status = 'dispatched';
                    $print_info = array(
                        'msg' => '出票失败',
                        'time_desc' => date('y-m-d H:i', strtotime($fail_time)),
                    );
                    $dispatch_info['msg'] = '不派奖';
                    $current_status = 'fail';
                    $current_statuscn = '交易失败';
                }
            }

            if (in_array($prize_status, array('Open', 'Prize'))) {//经过开、派奖环节

                $process_status = 'opened';//开过奖

                if (strtotime($open_time) > strtotime($create_time)) {//开奖

                    $open_info = array(
                        'time_desc' => date('y-m-d H:i', strtotime($open_time)),
                        'msg' => ($net_prize <= 0) ? '未中奖' : ($real_prize > 0 ? ($raw_prize > 10000 ? '大奖' . $net_prize : '中奖' . $net_prize) : ($raw_prize > 10000 ? '<span class="gray">' . '大奖' . $net_prize . '</span>' : '<span class="gray">' . '中奖' . $net_prize . '</span>')),
                    );
                    $process_status = 'dispatching';//等待派奖
                    if ($real_prize == 0 && $raw_prize > 0 && $net_prize > 0) {
                        $process_status = 'dispatched';
                        $dispatch_info['msg'] = '不派奖';
                        $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($open_time));
                    }

                    if ($raw_prize >= 0) {

                        if ($raw_prize == 0) {
                            $process_status = 'dispatched';
                            $dispatch_info['msg'] = '不派奖';
                            $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($open_time));
                        } else {
                            if (($net_prize != $raw_prize) || $get_ticket == 'Y') {
                                $dispatch_info['msg'] = '自兑奖';
                                $process_status = 'dispatched';
                                $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($open_time));
                            }
                        }
                    }
                    //针对出票失败做异常处理
                    if ($print_status == 'fail') {

                        $process_status = 'dispatched';
                        $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($open_time));
                        $current_status = 'fail';
                        $current_statuscn = '交易失败';
                    }

                }
                if (strtotime($prize_time) > strtotime($create_time)) {//派奖

                    $process_status = 'dispatched';//已派奖

                    $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($prize_time));

                    if ($raw_prize > 0 && $net_prize == $raw_prize) {

                        $dispatch_info['msg'] = '已派奖';
                    }
                }
            }

        } else {//其他异常情况
            $pay_info['msg'] = '付款失败';
            $pay_info['time_desc'] = date('y-m-d H:i', strtotime($fail_time));

            $print_info['msg'] = '出票失败';
            $print_info['time_desc'] = date('y-m-d H:i', strtotime($fail_time));
            $process_status = 'opening';

            $open_info['time_desc'] = '预计 ' . $open_info['time_desc'];
            $dispatch_info['time_desc'] = '预计 ' . $dispatch_info['time_desc'];


            if (strtotime($open_time) > strtotime($create_time)) {//开奖
                $open_info = array(
                    'time_desc' => date('y-m-d H:i', strtotime($open_time)),
                    'msg' => ($net_prize <= 0) ? '未中奖' : ($net_prize > 10000 ? '中大奖 ' . $net_prize : '中奖 ' . $net_prize),
                );
                $process_status = 'dispatched';//等待派奖
                $dispatch_info['time_desc'] = date('y-m-d H:i', strtotime($open_time));
            }

            $dispatch_info['msg'] = '不派奖';
        }

        //解析票信息
        $is_havingticket = 'N';
        $process_service = Service::instance()->find('lottery', strtolower($projectInfo['lotteryType']) . 'process');
        $ticket_list = $process_service->parseTicketContentByLotteryId($this->projectId);
        if (!empty($ticket_list['list'])) {
            $is_havingticket = 'Y';
        }
        $data = array();

        $data['project_id'] = $this->projectId;
        $data['pay_status'] = $pay_status;
        $data['print_status'] = $print_status;
        $data['is_havingticket'] = $is_havingticket;
        $data['add_time'] = date('Y-m-d H:i', strtotime($lottery_info['addTime']));
        $data['money'] = $money;
        $data['prize_money'] = $raw_prize;
        $data['current_status'] = $current_status;
        $data['current_statuscn'] = $current_statuscn;
        $data['process_status'] = $process_status;
        $data['submit_info'] = $submit_info;
        $data['pay_info'] = $pay_info;
        $data['print_info'] = $print_info;
        $data['open_info'] = $open_info;
        $data['dispatch_info'] = $dispatch_info;
        $data['tickeList'] = $ticket_list['list'];
        $str = $this->encrypt($data);//加密
        if (!empty($ticket_list)) {
            //$is_havingticket = 'Y';
            $this->ajaxReturn(array('code' => '0000', 'code_str' => "信息获取成功", 'info' => $str));
        } else {
            $this->ajaxReturn(array('code' => '0000', 'code_str' => "信息获取失败", 'ticket_list' => ''));
        }
    }

    /*
     * 奖金优化详情
    *  */
    public function prizereview()
    {
        $lottery_service = Service::instance()->find('lottery', 'lottery');

        $lottery_info = $lottery_service->getLotteryInfo($this->projectId);

        if (!in_array($lottery_info['manner'], array('1', '3'))) {
            $this->ajaxReturn(array("code" => "-1001", "code_str" => "此方案不是奖金优化的方案"));
        }
        $wagerInfo = $lottery_info['wagerCreateInfo'];
        $reviewInfo = explode('#', $wagerInfo['tool']['info']);
        $oddList = $wagerInfo['odds'];
        $reviewList = array();
        $lotteryMap = Service::instance()->loadConfig('lottery', 'process', 'lotteryMap');
        $oddCode = Service::instance()->loadConfig('lottery', 'process', 'getOddCode');
        $lotteryContent = Service::instance()->loadConfig('lottery', 'process', 'getContent');
        //查询比赛场次彩果
        $lotteryTypes = $wagerInfo['lotteryTypeStr'];        //做单时在wager记录  所有的参与彩种  eg：FTBRQSPF,FTSPF,FTBF
        $matchOrder = $lottery_info['matchSeq'];
        $lotteryNo = $lottery_info['lotteryNo'];
        $scheduleService = Service::instance()->find('schedule', 'match');
        $matchListRes = $scheduleService->getSportteryInfoListForZq($lotteryTypes, $lotteryNo, $matchOrder, false);

        $reviewInfoPrize = array();
        if ($lottery_info['prizeStatus'] == 'Open') {//已开奖，计算中奖信息
            //票数据校验
            $ticket_service = Service::instance()->find('ticket', 'ticket');
            $ticket_info = $ticket_service->getTicketDataByLotteryId($this->projectId);
        }

        foreach ($reviewInfo as $key => $val) {
            list($wagerStr, $count) = explode('|', $val);
            $wagerList = explode(';', $wagerStr);
            $reviewList[$key]['count'] = $count;
            if (count($wagerList) == 1) {
                $reviewList[$key]['passType'] = "单关";
            } else {
                $reviewList[$key]['passType'] = count($wagerList) . '串1';
            }
            $list = array();
            $yuce_prize = 1;
            foreach ($wagerList as $k => $v) {
                list($oid, $wager) = explode(':', $v);
                list($lotteryCode, $opts) = explode('@', $wager);
                $lotteryT = $lotteryMap[$lotteryCode];
                $list[$k]['oid'] = $oid;
                $list[$k]['oidCn'] = $oddList[$oid]['oidCn'];
                $list[$k]['lotteryType'] = $lotteryT;
                $list[$k]['homeName'] = $oddList[$oid]['homeName'];
                $list[$k]['awayName'] = $oddList[$oid]['awayName'];
                $list[$k]['rq'] = $oddList[$oid]['rq'];
                $optsList = explode(',', $opts);
                $result = $matchListRes[$oid]['bet_result'];
                foreach ($optsList as $ok => $opt) {
                    $optKey = array_search($opt, $oddCode[$lotteryT]);
                    $list[$k]['wager'][$ok]['opt'] = $lotteryContent[$lotteryT][$opt];
                    $list[$k]['wager'][$ok]['odd'] = $oddList[$oid][$lotteryT][$optKey];
                    $list[$k]['wager'][$ok]['result'] = $lotteryContent[$lotteryT][$opt];

                    if ($result !== '') {
                        $list[$k]['wager'][$ok]['hit'] = $result == $opt ? 1 : 2;//1是命中，2是不命中，其余未开奖
                    }
                }
                $yuce_prize = $yuce_prize * $list[$k]['wager'][$ok]['odd'];
            }
            $reviewList[$key]['prize'] = round($yuce_prize * 2 * $count, 2);
            $reviewList[$key]['list'] = $list;
            if ($ticket_info['count']) {
                foreach ($ticket_info['list'] as $ticket => $tInfo) {
                    if ($wagerStr == $tInfo['wager_store']) {
                        $reviewList[$key]['prize'] = $tInfo['raw_prize'];
                        break;
                    }
                }
            }
        }
        $this->ajaxReturn(array("code" => "0000", "code_str" => "suc", "info" => $reviewList, 'prizeStatus' => $lottery_info['prizeStatus']));
    }

    /**
     *合买方案详情
     */
    public function TogetherProjectInfo()
    {
        $lotteryServer = Service::instance()->find('lottery', 'lottery');
        $projectInfo = $lotteryServer->getLotteryInfo($this->projectId);
        $user_id = $this->userId;
        $nowTime = time();//当前时间
        if (empty($projectInfo) || $projectInfo['code'] == -1002) {
            $this->ajaxReturn(array('code' => '1001', 'code_str' => '此方案不存在或者已超过3个月的保存期限，暂时无法查询，由此带来的不便，敬请谅解!'));
        }
        $levelInfo = Service::instance()->loadConfig('lottery', 'lottery', 'getLotteryLevel', array($projectInfo['lotteryType']));
        $className = 'Project_' . $levelInfo['1'] . '_' . $projectInfo['lotteryType'];
        $projectShareInfo = $lotteryServer->getShareMoneyByLotteryId($this->projectId);//获取方案售卖详情
        if (strtotime($projectInfo['endTime']) - $nowTime > 0) {//方案截期前
            $projectShareMoney = $projectShareInfo['shar_amount'];
            $projectInfo['assure_num'] = intval($projectShareInfo['assure_amount']);
            if (!empty($user_id)) {
                //获取用户跟单信息
                $userShareInfo = $lotteryServer->getUserFollowInfo($user_id, $this->projectId);
                $projectInfo['shareNum'] = intval($userShareInfo['shar_amount']);//认购份数
            } else {
                $projectInfo['shareNum'] = 0;
            }
        } else {//截期后
            $projectShareMoney = $projectShareInfo['shar_amount'] + $projectShareInfo['assure_amount'];
            $projectInfo['assure_num'] = intval($projectShareInfo['assure_amount']);
            if (!empty($user_id)) {
                //获取用户跟单信息
                $userShareInfo = $lotteryServer->getUserFollowInfo($user_id, $this->projectId);
                $projectInfo['shareNum'] = intval($userShareInfo['shar_amount']) + $userShareInfo['assure_amount'];//认购份数+保底份数
            } else {
                $projectInfo['shareNum'] = 0;
            }
        }
        if (class_exists($className)) {
            $projectClass = new $className();
            $projectClass->run($projectInfo, $levelInfo);

            $projectClass->setWagerTpl();
            $projectInfo = $projectClass->setLotteryResultTpl();

            $projectInfo['wagerList'] = $projectInfo['wagerStr'];
            if (!empty($projectShareMoney)) {
                $projectInfo['completerate'] = number_format(abs($projectShareMoney) / abs($projectInfo['totalMoney']), 2) * 100;
                $projectInfo['completeNum'] = intval($projectInfo['totalMoney']) - intval($projectShareMoney);//剩余份数
            } else {
                $projectInfo['completerate'] = '0';
                $projectInfo['completeNum'] = intval($projectInfo['totalMoney']);
            }

            unset($projectInfo['wagerStr']);
            if (is_array($projectInfo['wagerList'])) {
                $projectInfo['wagerList'] = array_merge($projectInfo['wagerList']);
            }
//            dprint($projectInfo);
//            $str = $this->encrypt($projectInfo);//加密
            $this->ajaxReturn(array("code" => "0000", 'code_str' => '获取信息成功', 'info' => $projectInfo));
        }
    }

    /**
     *合买跟单列表
     */
    public function followProjectList()
    {
        //$this->projectId = '1143';
        $lotteryServer = Service::instance()->find('lottery', 'lottery');
        $user_service = Service::instance()->find('account', 'user');//用户信息
        $cash_service = Service::instance()->find('account', 'record');
        $projectInfo = $lotteryServer->getLotteryInfo($this->projectId);
        if (empty($projectInfo) || $projectInfo['code'] == -1002) {
            $this->ajaxReturn(array('code' => '1001', 'code_str' => '此方案不存在或者已超过3个月的保存期限，暂时无法查询，由此带来的不便，敬请谅解!'));
        }
        $prizeInfo=[];
        if ($projectInfo['netPrize'] > 0) {
            $requset_data = [
                'target_id' => $this->projectId,
                'category' => 'Prize',
            ];
            $prizeInfo = $cash_service->getPrizeCashList($requset_data);
        }
        //跟单用户明细
        $followList = $lotteryServer->getFollowList($this->projectId);
        // dprint($this->projectId,$followList);
        $data = [];
        foreach ($followList as $value) {
            if ($value['trade_type'] == 'share' && $value['money'] > 0) {
                $data[$value['user_id']]['shareNum'] += abs($value['money']);
                $data[$value['user_id']]['shareMoney'] += abs($value['money']);
                $data[$value['user_id']]['create_time'] = $value['create_time'];
            }
            if ($value['trade_type'] == 'share' && $value['money'] < 0) {
                $data[$value['user_id']]['shareNum'] -= abs($value['money']);
                $data[$value['user_id']]['shareMoney'] -= abs($value['money']);
                $data[$value['user_id']]['create_time'] = $value['create_time'];
            }

            $data[$value['user_id']]['prizeMoney'] = $prizeInfo[$value['user_id']]['con_total'] - $prizeInfo[$value['user_id']]['out_total'];
            $data[$value['user_id']]['create_time'] = $value['create_time'];
            if ($value['trade_type'] == 'assure' && $value['money'] > 0) {
                $data[$value['user_id']]['shareNum'] += abs($value['money']);
                $data[$value['user_id']]['shareMoney'] += abs($value['money']);
            }
            if ($value['trade_type'] == 'assure' && $value['money'] < 0) {
                $data[$value['user_id']]['shareNum'] -= abs($value['money']);
                $data[$value['user_id']]['shareMoney'] -= abs($value['money']);
            }
            if (empty($data[$value['user_id']]['prizeMoney'])) {
                $data[$value['user_id']]['prizeMoney'] = '0';
            }
        }
        $info = [];
        foreach ($data as $k => $v) {
            $v['user_id'] = $k;
            $userInfo = $user_service->getInfoByID($k);
            $v['user_name'] = $userInfo['user_name'];
            $v['create_time'] = substr($v['create_time'], 5, 11);
            $info[] = $v;
        }
        $this->ajaxReturn(array("code" => "0000", "code_str" => "suc", "info" => $info));
    }

}
